import { join_house, polling_house } from "./ready"
import { sign_err_log } from '../controller/errLog.js'
import mongoose from 'mongoose'
import {
  wait_add_score,
  click_game_begin,
  get_begin_house_info,
  save_draw_steps,
  onece_again,
  draw_revoke
} from "./begin"
const ws = require("nodejs-websocket")

ws.createServer(function(conn) {
  conn.on("text", function(msg) {
    // console.log("收到的信息为:" + msg)

    const str = JSON.parse(msg)
    if (str.type === "ping") {
      if (str.data.openid && str.data.house_id) {
        polling_house(conn, str.data)
      }
    }
    // 加入房间
    if (str.type === "join_house") {
      join_house(conn, str.data)
    }
    // 用户点击开始游戏
    if (str.type === "game_begin") {
      click_game_begin(conn, str.data)
    }
    if (str.type === 'get_begin_house_info') {
      get_begin_house_info(conn, str.data)
    }
    // 猜对将分数计入临时存放区
    if (str.type === "draw_steps") {
      save_draw_steps(conn, str.data)
    }
    // 猜对将分数计入临时存放区,猜错不计，并将用户输入发送给其他人
    if (str.type === "answer") {
      wait_add_score(conn, str.data)
    }

    if (str.type === "onece_again") {
      onece_again(conn, str.data)
    }
    if (str.type === "draw_revoke") {
      draw_revoke(conn, str.data)
    }
  })
  conn.on("close", function(code, reason) {
    console.log(code, reason, "关闭连接")
  })
  conn.on("error", async (code, reason) => {
    const errLog = mongoose.model('errLog')
    // ws经常报错，所以只记录最新的一次
    const res_remove =  await errLog.remove({funcName:'ws-error'})
    // 新增一条已解决的记录
    sign_err_log({ funcName: 'ws-error', errCont: reason, status: 0, allCont: reason,happenCount:res_remove.n })
    console.log("ws异常关闭原因", reason, code, "ws异常关闭原因111")
  })
}).listen(3001)

